# -*- coding:utf-8 -*-
# app.py
from controller import web_controller
from utils.common.init_app import app
from flask_restful import Api
from utils.common.db_connection import db
from exception.api_exception import APIException, HTTPException
from flask import jsonify
import urllib3
import env_config


# 全局错误AOP处理
@app.errorhandler(Exception)
def framework_error(e):
    # api_logger.error("error info: %s" % e)  # 对错误进行日志记录
    if isinstance(e, APIException):
        response = jsonify(e.to_dict())
        response.status_code = e.code
        return response
    elif isinstance(e, HTTPException):
        code = e.code
        msg = e.description
        # error_code = 9999
        ne = APIException(msg, code)
        response = jsonify(ne.to_dict())
        response.status_code = e.code
        return response
    else:
        ne = APIException("未知错误.", 9999)
        response = jsonify(ne.to_dict())
        return response


def create_app():
    # 初始化db
    app.config.from_mapping(env_config.config_mapping())
    db.app = app
    db.init_app(app)
    # 初始化jwt
    # jwt.init_app(app)
    # 其他的app配置和定义

    api = Api(app)
    api.add_resource(web_controller.Health, '/health')  # 问卷星发送任务
    api.add_resource(web_controller.StartTaskWjx, '/api/v1/start_task_wjx')  # 问卷星发送任务
    api.add_resource(web_controller.TaskStop, '/api/v1/stop_send_result')  # 停止任务
    api.add_resource(web_controller.TestExecjsEnv, '/api/v1/execjs_env')  # 测试execjs使用的引擎

    urllib3.disable_warnings()
    return app
